<template>
  <div class="body">
    <div class="empty-space"></div>
    <div class="search-header">
      <span class="search-label">选择地区搜索：</span>
      <el-cascader
        size="large"
        :options="options"
        v-model="selectedOptions"
        @change="searchPoets"
        placeholder="请选择地区"
      >
      </el-cascader>
    </div>
    <div class="search-input">
      <span class="search-label">输入关键词搜索：</span>
      <el-select
        v-model="searchType"
        placeholder="请选择搜索类型"
        class="search-select"
        @change="handleInput"
      >
        <el-option label="地名" value="place"></el-option>
        <el-option label="人名" value="person"></el-option>
      </el-select>
      <el-input
        v-model="searchKey"
        placeholder="请输入关键词"
        class="search-input-box"
        @change="handleInput"
      ></el-input>
      <el-button
        @click="search"
        class="search-button"
        :disabled="searchType === '' || searchKey === ''"
        >搜索</el-button
      >
    </div>
    <div v-if="poets.length > 0">
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          layout="prev, pager, next ,jumper"
          v-model:page-count="totalPages"
          @current-change="handlePaginationChange"
        />
        <span class="TotalPages"
          >总页数：<span>{{ totalPages }}</span></span
        >
      </div>
      <div
        v-loading="Loading"
        v-for="poet in displayedPoets"
        :key="poet.id"
        class="poet"
      >
        <h3>{{ poet.name }}</h3>
        <img v-if="poet.image" :src="poet.image" :alt="poet.name" />
        <p>{{ poet.summary }}</p>
        <router-link :to="'/PoetDetails/' + poet.id" class="link"
          >查看详情➩</router-link
        >
      </div>
    </div>
    <div v-else v-loading="Loading">
      <p v-if="showMessage == true && Loading == false" class="no-poet-message">
        抱歉，暂无诗人收录。
      </p>
    </div>
    <div class="empty-space"></div>
  </div>
</template>

<script>
import axios from "axios";
import { address } from "@/assets/json/address.js";
import { Loading } from "@element-plus/icons-vue";
export default {
  data() {
    return {
      poets: [],
      currentPage: 1,
      perPage: 15,
      totalPages: 0, //总页数
      page: [], //获取的页数数组
      inputPage: null, //跳转页数
      options: address, //级联选择器选项
      selectedOptions: [-1], //级联选择器选中的数据
      lastSelect: -1, //级联选择器上次搜索
      showScrollButton: false, // 悬浮按钮
      searchKey: "", // 搜索关键词
      searchType: "", // 搜索类型
      lastKey: -1, //上次输入关键词
      lastType: -1, //上次输入类型
      showMessage: false, //显示无数据的页面提示信息
      flag: -1, //输入关键词类型
      Loading: false, //缓冲
      locationId: this.$route.query.location_id, //获取主页传递的行政编码
    };
  },
  computed: {
    displayedPoets() {
      return this.poets;
    },
  },
  mounted() {
    if (this.locationId) {
      //根据是否有传值判断构建函数
      this.morePoets(); //查看该地更多诗人函数（和主页抽屉链接的）
      this.searchPages(this.locationId);
    } else {
      this.fetchPoets(); //全部诗人函数
      this.fetchPages(); //全部诗人库页数
    }
    this.showMessageDelay(); //延迟显示无数据提示信息
  },
  methods: {
    //无数据提示信息延迟显示
    showMessageDelay() {
      // 延迟3秒显示提示信息
      setTimeout(() => {
        this.showMessage = true;
      }, 2000);
    },
    //输入框有数据时，清空级联选择器
    handleInput() {
      this.selectedOptions = [-1];
    },
    //获取总页数
    fetchPages() {
      let currentPage = this.currentPage - 1;
      axios
        .get("poetry_all/" + currentPage + "/" + this.perPage + "/" + 0)
        .then((response) => {
          this.page = response.data;
          this.totalPages = this.page[0].page_num;
          console.log("totalPage:", this.totalPages);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //级联选择器地区的诗人页数
    searchPages(value) {
      console.log("select_id:", value);
      console.log("link:", "location/" + Number(value) + "/" + this.perPage);
      axios
        .get("location/" + Number(value) + "/" + this.perPage)
        .then((response) => {
          this.totalPages = response.data.page_num;
          console.log("selectPage:", this.totalPages);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //输入搜索的诗人页数
    inputPages(value) {
      console.log("input:", value);
      axios
        .get("search/" + value + "/" + this.flag + "/" + this.perPage)
        .then((response) => {
          this.totalPages = response.data.page_num;
          console.log("inputPage:", this.totalPages);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //获取诗人
    fetchPoets() {
      this.Loading = true;
      this.flag = -1;
      let currentPage = this.currentPage - 1;
      console.log("currentpage:", currentPage);
      axios
        .get("poetry_all/" + currentPage + "/" + this.perPage + "/" + 1)
        .then((response) => {
          this.Loading = false;
          this.poets = response.data;
          this.fetchPages(); //重置总页数
          console.log("poetry:", this.poets);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //分页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.handlePaginationChange();
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.handlePaginationChange();
      }
    },
    jumpToPage() {
      if (this.inputPage >= 1 && this.inputPage <= this.totalPages) {
        this.currentPage = this.inputPage;
        this.inputPage = null;
        this.handlePaginationChange();
      }
    },
    handlePaginationChange() {
      console.log("currentPage:", this.currentPage);
      console.log("searchValue:", this.selectedOptions[1]);
      if (this.flag != -1) {
        // 输入搜索
        this.search();
      } else if (this.selectedOptions[0] != -1) {
        // 级联搜索
        this.searchPoets();
      } else {
        // 普通搜索
        this.fetchPoets();
      }
    },
    //根据级联选择器的地区搜索诗人
    searchPoets() {
      this.Loading = true;
      this.searchKey = "";
      this.searchType = ""; //清空输入搜索框
      this.flag = -1;
      console.log("search1:", this.selectedOptions[1]);
      console.log("search0:", this.selectedOptions[0]);
      if (this.selectedOptions[0] == -1) {
        //等于-1是全部
        this.currentPage = 1;
        this.fetchPoets();
      } else {
        let select = this.selectedOptions[0];
        if (this.selectedOptions[0] != 0) {
          //等于0是家乡不详的诗人
          select = this.selectedOptions[1]; //记录选择的地区
        }
        if (select != this.lastSelect) {
          this.currentPage = 1; //和上次搜索不是同一地区，从第一页开始
          this.lastSelect = select;
        }
        console.log("select:", select);
        axios
          .post("location/" + Number(select) + "/" + 0, {
            page: this.currentPage - 1,
            perPage: this.perPage,
          })
          .then((response) => {
            this.Loading = false;
            console.log("searchCurrentPage:", this.currentPage);
            console.log("searchPertPage:", this.perPage);
            this.poets = response.data;
            console.log("searchpoetry:", this.poets);
            this.searchPages(select); //根据地区重置页数
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
    //根据输入搜索诗人
    search() {
      this.Loading = true;
      console.log("searchKey:", this.searchKey);
      console.log("searchType:", this.searchType);
      if (this.searchType === "place") this.flag = 1; //1是地区搜索
      else this.flag = 0;
      if (this.lastKey != this.searchKey && this.lastType != this.searchType) {
        this.lastKey = this.searchKey;
        this.lastType = this.searchType;
        this.currentPage = 1;
      }
      console.log("flag:", this.flag);
      axios
        .post("search/" + this.searchKey + "/" + this.flag, {
          page: this.currentPage - 1,
          perPage: this.perPage,
        })
        .then((response) => {
          this.Loading = false;
          this.poets = response.data;
          console.log("poetry:", this.poets);
          this.inputPages(this.searchKey); //根据地区重置页数
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //主页查看更多诗人
    morePoets() {
      this.Loading = true;
      if (this.locationId) {
        this.selectedOptions[1] = this.locationId; //市
        this.selectedOptions[0] = this.locationId.substring(0, 2); //省
      } else return; //没传值，是全部诗人库，该函数结束
      console.log("moreId:", this.locationId); //看能否取值
      axios
        .post("location/" + Number(this.locationId) + "/" + 0, {
          page: this.currentPage - 1,
          perPage: this.perPage,
        })
        .then((response) => {
          this.Loading = false;
          console.log("moreCurrentPage:", this.currentPage);
          this.poets = response.data;
          console.log("morepoetry:", this.poets);
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style scoped>
.body {
  background-color: rgb(226, 230, 219);
  height: auto;
}

/*空白条 */
.empty-space {
  height: 60px;
}

/*级联选择器 */
.search-header {
  text-align: left;
  margin-left: 10%;
  margin-bottom: 20px;
}

.el-cascader {
  width: 100%;
}

/*输入搜索框 */
.search-input {
  display: flex;
  align-items: center;
  width: 60%;
  text-align: left;
  margin-left: 10%;
  margin-bottom: 30px;
}

/*搜索提示语*/
.search-label {
  margin-right: 10px;
}

/*关键词 */
.search-select {
  width: 150px;
}

/*输入 */
.search-input-box {
  margin-left: 10px;
  width: 150px;
}

/*搜索按钮 */
.search-button {
  margin-left: 10px;
  background-color: #55796b;
  color: #fff;
}

.search-button:hover {
  background-color: #2c4831;
  color: #fff;
}

/*不可使用时按钮样式 */
.search-button:disabled {
  background-color: #55796b;
  color: #fff;
  opacity: 0.5;
  /* 降低不透明度 */
  cursor: not-allowed;
  /* 光标禁止符号 */
}

.search-button:disabled:hover {
  background-color: #55796b;
}

/*总页数 */
.TotalPages {
  font-weight: bold;
}

/*分页 */
.pagination {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  align-items: center;
  margin-right: 10%;
  margin-bottom: 20px;
}

/*诗人卡片 */
.poet {
  margin-bottom: 20px;
  /*外边距 */
  padding: 20px;
  /*内边距 */
  border: 1px solid #ccc;
  border-radius: 8px;
  /*圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /*阴影效果 */
  transition: box-shadow 0.3s ease;
  /*阴影过渡 */
  width: 80%;
  margin-left: auto;
  margin-right: auto;
  background-color: #f0f0f0;
}

.poet:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

/*诗人名字 */
.poet h3 {
  font-size: 20px;
  margin-bottom: 10px;
}

.poet img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
}

/*诗人简介 */
.poet p {
  margin-top: 10px;
}

/*查看详情 */
.link {
  color: #007bff;
  transition: color 0.3s ease;
  /* 添加颜色过渡效果 */
}

.link:hover {
  color: #00b395;
}

/*无收录提示信息 */
.no-poet-message {
  font-size: 18px;
  color: #888;
  font-style: italic;
  height: 400px;
}
</style>
